#include <stdio.h>
#include <stdlib.h>
#include "compiler.h"

struct compile_process *compile_process_create(const char *filename, const char *out_filename, int flags)
{
    // 读入待编译文件
    FILE *file = fopen(filename, "r");
    if (file == NULL)
    {
        printf("待编译文件为空\n%s", filename);
        return COMPILER_FAILED_WITH_ERRORS;
    }
    printf("读入%s程序成功\n", filename);

    FILE *out_file = NULL;
    // 写出编译后文件
    if (out_filename)
    {
        out_file = fopen(out_filename, "w");
        if (out_file == NULL)
        {
            return COMPILER_FAILED_WITH_ERRORS;
        }
        printf("写出%s程序成功\n", out_filename);
    }

    // 创建编译过程
    struct compile_process *process = calloc(1, sizeof(struct compile_process));
    process->flags = flags;
    process->cfile.fp = file;
    process->ofile = out_file;
    printf("编译过程创建成功\n");
    return process;
}

char compile_process_next_char(struct lex_process *process)
{
    struct compile_process *compiler = process->compiler;
    compiler->pos.col += 1;            // 增加列号
    char c = getc(compiler->cfile.fp); // 读取下一个字符
    if (c == '\n')                     // 如果字符是换行符
    {
        compiler->pos.line++;  // 行号+1
        compiler->pos.col = 1; // 列号归1
    }
    return c;
}

char compile_process_peek_char(struct lex_process *process)
{
    struct compile_process *compiler = process->compiler;
    char c = getc(compiler->cfile.fp); // 读取下一个字符
    ungetc(c, compiler->cfile.fp);     // 将字符推回到输入流中
    return c;
}

void compile_process_push_char(struct lex_process *process, char c)
{
    struct compile_process *compiler = process->compiler;
    ungetc(c, compiler->cfile.fp); // 将字符推回到输入流中
}
